package crawler.web.framework;

import java.util.LinkedList;

import javax.annotation.Resource;

import library.Tracer;
import library.thread.flow.ParameterBox;

import org.springframework.stereotype.Component;

import crawler.web.beans.CrawlPageContext;
import crawler.web.component.CommonHtmlProcessor;
import crawler.web.component.IComponent;
import crawler.web.engine.config.SpBN;

/**
 * @author waynechen Mar 5, 2012 5:27:44 PM
 */
@Component("Dispatcher")
public class Dispatcher {

	@Resource(name = SpBN.bean_comps)
	private LinkedList<IComponent> comps;

	/**
	 * 进一步处理
	 * 
	 * @author waynechen
	 * @param params
	 * @throws Exception
	 */
	public void dispatch(ParameterBox params) throws Exception {
		//此处实现分发机制
		CrawlPageContext page = (CrawlPageContext) params.peek("pageContext");

		IComponent tmp = null;
		for (IComponent comp : comps) {

			if (comp.getClass().equals(CommonHtmlProcessor.class)) {
				tmp = comp;
				continue;
			}

			//如果某个组件能接受此任务
			//则不让其它组件接受此任务
			if (comp.accept(page.getUrl())) {
				comp.process(params);
				return;
			}
		}

		if (tmp != null && tmp.accept(page.getUrl())) {
			tmp.process(params);
			return;
		}

		Tracer.info("Dispatcher 找不到合适的组件来处理: " + page.getUrl().getOriUrl());
	}
}
